using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Catastrophe.BasePC.UI.Model;
using Catastrophe.BasePC.UI.SystemIni;
using Catastrophe.Common;
using Catastrophe.Common.AttributeEx;
using Catastrophe.Initialize;
using SqlSugar;
using SqlSugarEx;
using SqlSugarEx.Utilities;

namespace Catastrophe.BasePC.UI.DbDal
{
	public class SysAuthorityTemplateDal : IBaseAuthorityDal
	{
		protected SqlSugarClientEx _dbSugar;

		public SysAuthorityTemplateDal()
		{
			this._dbSugar = DbUtility.GetSugar(Catastrophe.Initialize.SystemIni.FileConfigIni.GetDbAppConfig, isAutoCloseCon: true);
		}

		public DataTable QueryTemplateNow()
		{
			return this._dbSugar.Queryable<SysAuthorityTemplateEntity>().ToDataTable();
		}

		public DataTable GetUserAuthority(string userName, string userNo, string depart, string identity, string authorizeType)
		{
			DataTable dataTable = new DataTable();
			AuthorizeTypeEnum? authorizeTypeEnum;
			if (string.IsNullOrWhiteSpace(authorizeType) || authorizeType == BuildAttribute.GetEnumDescribeStr<AuthorizeTypeEnum>(AuthorizeTypeEnum.User))
			{
				if (userName == null)
				{
					throw new ArgumentNullException("userName");
				}
				if (userNo == null)
				{
					throw new ArgumentNullException("userNo");
				}
				authorizeTypeEnum = AuthorizeTypeEnum.User;
				dataTable = (from x in this._dbSugar.QueryableBind<SysRoleAuthorityEntity>()
					where x.UserNo == userNo && x.UserName == userName && !x.Ignore
					select x).ToDataTable();
			}
			else if (authorizeType == BuildAttribute.GetEnumDescribeStr<AuthorizeTypeEnum>(AuthorizeTypeEnum.Depart))
			{
				if (depart == null)
				{
					throw new ArgumentNullException("depart");
				}
				authorizeTypeEnum = AuthorizeTypeEnum.Depart;
				dataTable = (from x in this._dbSugar.QueryableBind<SysRoleAuthorityEntity>()
					where x.Depart == depart && !x.Ignore
					where SqlFunc.IsNullOrEmpty(x.UserName)
					where SqlFunc.IsNullOrEmpty(x.UserNo)
					where x.AuthorizeType == authorizeType
					select x).ToDataTable();
			}
			else
			{
				if (!(authorizeType == BuildAttribute.GetEnumDescribeStr<AuthorizeTypeEnum>(AuthorizeTypeEnum.Identity)))
				{
					throw new Exception("invalid query params!");
				}
				if (depart == null)
				{
					throw new ArgumentNullException("depart");
				}
				authorizeTypeEnum = AuthorizeTypeEnum.Identity;
				dataTable = (from x in this._dbSugar.QueryableBind<SysRoleAuthorityEntity>()
					where x.Identity == identity && !x.Ignore
					where SqlFunc.IsNullOrEmpty(x.UserName)
					where SqlFunc.IsNullOrEmpty(x.UserNo)
					where x.AuthorizeType == authorizeType
					select x).ToDataTable();
			}
			bool? flag = (from x in this._dbSugar.Queryable<SysUserEntity>()
				where x.UserName == userName
				where x.UserNo == userNo
				select x).First()?.AuthorizeRefresh;
			if (dataTable.Rows.Count == 0 || flag == true)
			{
				List<SysAuthorityTemplateEntity> list = new List<SysAuthorityTemplateEntity>();
				List<SysAuthorityTemplateEntity> list2 = (from x in this._dbSugar.Queryable<SysAuthorityTemplateEntity>()
					where !x.Ignore
					select x).ToList();
				if (list2.Count == 0)
				{
					return DataConverter.ConvertToDataFrame<SysAuthorityTemplateEntity>();
				}
				if (dataTable.Rows.Count == 0)
				{
					list = list2;
				}
				else if (flag == true)
				{
					list = new List<SysAuthorityTemplateEntity>();
					foreach (SysAuthorityTemplateEntity item in list2)
					{
						DataRow dataRow = dataTable.Select("property_name='" + item.PropertyName + "'").FirstOrDefault();
						if (dataRow == null)
						{
							list.Add(item);
						}
					}
				}
				List<SysRoleAuthorityEntity> list3 = new List<SysRoleAuthorityEntity>();
				foreach (SysAuthorityTemplateEntity item2 in list)
				{
					SysRoleAuthorityEntity sysRoleAuthorityEntity = new SysRoleAuthorityEntity
					{
						BaseIndex = item2.BaseIndex,
						ParentIndex = item2.ParentIndex,
						NodeName = item2.NodeName,
						NodeState = false,
						Depart = depart,
						Identity = identity,
						AuthorizeType = authorizeType,
						AssemblyName = item2.AssemblyName,
						PropertyName = item2.PropertyName
					};
					if (authorizeTypeEnum == AuthorizeTypeEnum.User)
					{
						sysRoleAuthorityEntity.UserName = userName;
						sysRoleAuthorityEntity.UserNo = userNo;
					}
					list3.Add(sysRoleAuthorityEntity);
				}
				int num = this._dbSugar.Insertable(list3).ExecuteCommand();
				if (num > 0 && flag == true)
				{
					(from x in this._dbSugar.Updateable<SysUserEntity>().SetColumns((SysUserEntity x) => new SysUserEntity
						{
							AuthorizeRefresh = false
						})
						where x.UserName == userName
						where x.UserNo == userNo
						select x).ExecuteCommand();
				}
				if (authorizeTypeEnum == AuthorizeTypeEnum.User)
				{
					dataTable = (from x in this._dbSugar.QueryableBind<SysRoleAuthorityEntity>()
						where x.UserNo == userNo && x.UserName == userName
						select x).ToDataTable();
				}
				else if (authorizeTypeEnum == AuthorizeTypeEnum.Depart)
				{
					dataTable = (from x in this._dbSugar.QueryableBind<SysRoleAuthorityEntity>()
						where x.Depart == depart && !x.Ignore
						where SqlFunc.IsNullOrEmpty(x.UserName)
						where SqlFunc.IsNullOrEmpty(x.UserNo)
						where x.AuthorizeType == authorizeType
						select x).ToDataTable();
				}
				else if (authorizeTypeEnum == AuthorizeTypeEnum.Identity)
				{
					dataTable = (from x in this._dbSugar.QueryableBind<SysRoleAuthorityEntity>()
						where x.Identity == identity && !x.Ignore
						where SqlFunc.IsNullOrEmpty(x.UserName)
						where SqlFunc.IsNullOrEmpty(x.UserNo)
						where x.AuthorizeType == authorizeType
						select x).ToDataTable();
				}
			}
			return dataTable;
		}

		public bool UpdateBind()
		{
			return this._dbSugar.UpdateBind();
		}

		public bool TranInsertTemplate(List<SysAuthorityTemplateEntity> templateList)
		{
			try
			{
				this._dbSugar.Ado.BeginTran();
				IEnumerable<string> assemblyBuff = templateList.Select((SysAuthorityTemplateEntity x) => x.AssemblyName).Distinct();
				(from x in this._dbSugar.Deleteable<SysAuthorityTemplateEntity>()
					where SqlFunc.ContainsArray(assemblyBuff.ToArray(), x.AssemblyName)
					select x).ExecuteCommand();
				(from x in this._dbSugar.Deleteable<SysRoleAuthorityEntity>()
					where SqlFunc.ContainsArray(assemblyBuff.ToArray(), x.AssemblyName)
					select x).ExecuteCommand();
				this._dbSugar.Insertable(templateList).ExecuteCommand();
				this._dbSugar.Ado.CommitTran();
				return true;
			}
			catch (Exception)
			{
				this._dbSugar.Ado.RollbackTran();
				return false;
			}
		}

		public Tuple<bool, string, List<SysAuthorityTemplateEntity>> CreateTemplate<T>(T t) where T : class, new()
		{
			Type type = t.GetType();
			List<SysAuthorityTemplateEntity> list = new List<SysAuthorityTemplateEntity>();
			Attribute customAttribute = Attribute.GetCustomAttribute(type, typeof(UserAuthorityTemplateAttribute));
			if (customAttribute == null)
			{
				return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: false, "模板为标注为UserPowerTemplateAttribute", list);
			}
			PropertyInfo[] properties = type.GetProperties();
			foreach (PropertyInfo element in properties)
			{
				TreeNodeAttribute treeNodeAttribute = Attribute.GetCustomAttribute(element, typeof(TreeNodeAttribute)) as TreeNodeAttribute;
				if (treeNodeAttribute != null)
				{
					list.Add(new SysAuthorityTemplateEntity
					{
						BaseIndex = treeNodeAttribute.BaseIndex,
						ParentIndex = treeNodeAttribute.ParentIndex,
						NodeName = treeNodeAttribute.NodeName
					});
				}
			}
			bool flag = false;
			if (list.Count <= 0)
			{
				return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: false, "未检索到有效UserPowerAttribute信息", list);
			}
			if (!this.TranInsertTemplate(list))
			{
				return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: false, "保存信息失败！", list);
			}
			return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: true, "", list);
		}

		public Tuple<bool, string, List<SysAuthorityTemplateEntity>> CreateTemplate(Dictionary<string, Type> dic)
		{
			try
			{
				List<SysAuthorityTemplateEntity> list = new List<SysAuthorityTemplateEntity>();
				foreach (string key in dic.Keys)
				{
					Type type = dic[key];
					if (type == null)
					{
						continue;
					}
					Attribute customAttribute = Attribute.GetCustomAttribute(type, typeof(UserAuthorityTemplateAttribute));
					if (customAttribute == null)
					{
						return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: false, "模板未标注为UserPowerTemplateAttribute", list);
					}
					PropertyInfo[] properties = type.GetProperties();
					foreach (PropertyInfo propertyInfo in properties)
					{
						TreeNodeAttribute treeNodeAttribute = Attribute.GetCustomAttribute(propertyInfo, typeof(TreeNodeAttribute)) as TreeNodeAttribute;
						if (treeNodeAttribute != null)
						{
							list.Add(new SysAuthorityTemplateEntity
							{
								BaseIndex = treeNodeAttribute.BaseIndex,
								ParentIndex = treeNodeAttribute.ParentIndex,
								NodeName = treeNodeAttribute.NodeName,
								AssemblyName = key,
								PropertyName = propertyInfo.Name
							});
						}
					}
				}
				if (list.Count <= 0)
				{
					return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: false, "未检索到有效UserPowerAttribute信息", list);
				}
				if (!this.TranInsertTemplate(list))
				{
					return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: false, "保存信息失败！", list);
				}
				return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: true, "", list);
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

		public Tuple<bool, string, List<SysAuthorityTemplateEntity>> CreateTemplate(Dictionary<string, List<IUserAuthorityTemplate>> dic)
		{
			try
			{
				List<SysAuthorityTemplateEntity> list = new List<SysAuthorityTemplateEntity>();
				foreach (string key in dic.Keys)
				{
					List<IUserAuthorityTemplate> list2 = dic[key];
					foreach (IUserAuthorityTemplate item in list2)
					{
						Type type = item.GetType();
						Attribute customAttribute = Attribute.GetCustomAttribute(type, typeof(UserAuthorityTemplateAttribute));
						if (customAttribute == null)
						{
							return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: false, "模板未标注为UserPowerTemplateAttribute", list);
						}
						PropertyInfo[] properties = type.GetProperties();
						PropertyInfo[] array = properties;
						foreach (PropertyInfo propertyInfo in array)
						{
							TreeNodeAttribute treeNodeAttribute = Attribute.GetCustomAttribute(propertyInfo, typeof(TreeNodeAttribute)) as TreeNodeAttribute;
							if (treeNodeAttribute != null)
							{
								list.Add(new SysAuthorityTemplateEntity
								{
									BaseIndex = treeNodeAttribute.BaseIndex,
									ParentIndex = treeNodeAttribute.ParentIndex,
									NodeName = treeNodeAttribute.NodeName,
									AssemblyName = key,
									PropertyName = propertyInfo.Name
								});
							}
						}
					}
				}
				if (list.Count <= 0)
				{
					return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: false, "未检索到有效UserPowerAttribute信息", list);
				}
				if (!this.TranInsertTemplate(list))
				{
					return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: false, "保存信息失败！", list);
				}
				return new Tuple<bool, string, List<SysAuthorityTemplateEntity>>(item1: true, "", list);
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

		[Obsolete("use UserAuthorityLoad(Dictionary<string, List<IUserAuthorityTemplate>> dic, string userName, string userNo) instead")]
		public Dictionary<string, object> UserAuthorityLoad(Dictionary<string, Type> dic, string userName, string userNo)
		{
			List<SysRoleAuthorityEntity> list = (from x in this._dbSugar.Queryable<SysRoleAuthorityEntity>()
				where x.UserName == userName
				where x.UserNo == userNo
				orderby x.AssemblyName
				select x).ToList();
			if (list.Count == 0)
			{
				return null;
			}
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			foreach (string each in dic.Keys)
			{
				List<SysRoleAuthorityEntity> list2 = list.Where((SysRoleAuthorityEntity x) => x.AssemblyName == each).ToList();
				if (list2.Count == 0)
				{
					continue;
				}
				object obj = Activator.CreateInstance(dic[each]);
				PropertyInfo[] properties = dic[each].GetProperties();
				PropertyInfo[] array = properties;
				foreach (PropertyInfo property in array)
				{
					SysRoleAuthorityEntity sysRoleAuthorityEntity = list2.FirstOrDefault((SysRoleAuthorityEntity x) => x.PropertyName == property.Name);
					if (sysRoleAuthorityEntity != null)
					{
						AuthorityConfig value = new AuthorityConfig
						{
							Valid = (sysRoleAuthorityEntity.NodeState && !sysRoleAuthorityEntity.Ignore),
							UserName = sysRoleAuthorityEntity.UserName,
							UserNo = sysRoleAuthorityEntity.UserNo
						};
						property.SetValue(obj, value);
					}
				}
				if (!dictionary.Keys.Contains(dic[each].Name))
				{
					dictionary.Add(dic[each].Name, obj);
				}
			}
			return dictionary;
		}

		public Dictionary<string, object> UserAuthorityLoad(Dictionary<string, List<IUserAuthorityTemplate>> dic, string userName, string userNo)
		{
			List<SysRoleAuthorityEntity> list = (from x in this._dbSugar.Queryable<SysRoleAuthorityEntity>()
				where x.UserName == userName
				where x.UserNo == userNo
				orderby x.AssemblyName
				select x).ToList();
			if (list.Count == 0)
			{
				return null;
			}
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			foreach (string each in dic.Keys)
			{
				List<SysRoleAuthorityEntity> list2 = list.Where((SysRoleAuthorityEntity x) => x.AssemblyName == each).ToList();
				if (list2.Count == 0)
				{
					continue;
				}
				List<IUserAuthorityTemplate> list3 = dic[each];
				foreach (IUserAuthorityTemplate item in list3)
				{
					string name = item.GetType().Name;
					PropertyInfo[] properties = item.GetType().GetProperties();
					PropertyInfo[] array = properties;
					foreach (PropertyInfo property in array)
					{
						SysRoleAuthorityEntity sysRoleAuthorityEntity = list2.FirstOrDefault((SysRoleAuthorityEntity x) => x.PropertyName == property.Name);
						if (sysRoleAuthorityEntity != null)
						{
							AuthorityConfig value = new AuthorityConfig
							{
								Valid = (sysRoleAuthorityEntity.NodeState && !sysRoleAuthorityEntity.Ignore),
								UserName = sysRoleAuthorityEntity.UserName,
								UserNo = sysRoleAuthorityEntity.UserNo
							};
							property.SetValue(item, value);
						}
					}
					if (!dictionary.Keys.Contains(name))
					{
						dictionary.Add(name, item);
					}
				}
			}
			return dictionary;
		}

		[Obsolete]
		public Dictionary<string, dynamic> UserAuthorityLoad2(Dictionary<string, Type> dic, string userName, string userNo)
		{
			List<SysRoleAuthorityEntity> list = (from x in this._dbSugar.Queryable<SysRoleAuthorityEntity>()
				where x.UserName == userName
				where x.UserNo == userNo
				orderby x.AssemblyName
				select x).ToList();
			if (list.Count == 0)
			{
				return null;
			}
			Type type = dic.Values.First((Type x) => x != null);
			object obj = null;
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			PropertyInfo[] array = null;
			foreach (SysRoleAuthorityEntity item in list)
			{
				if (!dic.Keys.Contains(item.AssemblyName))
				{
					continue;
				}
				Type type2 = dic[item.AssemblyName];
				if (type2 == null)
				{
					continue;
				}
				if (!type2.Name.Equals(type.Name))
				{
					if (obj != null)
					{
						dictionary.Add(type.Name, obj);
					}
					type = type2;
					obj = null;
					array = null;
				}
				if (obj == null)
				{
					obj = Activator.CreateInstance(type);
				}
				if (array == null)
				{
					array = type.GetProperties();
				}
				AuthorityConfig authorityConfig = new AuthorityConfig();
				if (item.NodeName == "用户管理")
				{
				}
				PropertyInfo[] array2 = array;
				foreach (PropertyInfo propertyInfo in array2)
				{
					authorityConfig.Valid = item.NodeState;
					authorityConfig.UserName = item.UserName;
					authorityConfig.UserNo = item.UserNo;
					propertyInfo.SetValue(obj, authorityConfig);
				}
			}
			if (!dictionary.Keys.Contains(type.Name))
			{
				dictionary.Add(type.Name, obj);
			}
			return dictionary;
		}

		public DataTable UserAuthorityRefresh(string userName, string userNo)
		{
			return (from x in this._dbSugar.Queryable<SysRoleAuthorityEntity>().WhereIF(!string.IsNullOrEmpty(userName), (SysRoleAuthorityEntity x) => x.UserName == userName).WhereIF(!string.IsNullOrEmpty(userNo), (SysRoleAuthorityEntity x) => x.UserNo == userNo)
				orderby x.AssemblyName
				select x).ToDataTable();
		}

		public int SetIgnoreState(List<int> pkList, bool state, int flag)
		{
			switch (flag)
			{
			case 1:
			{
				List<SysAuthorityTemplateEntity> list = new List<SysAuthorityTemplateEntity>();
				pkList.ForEach(delegate(int x)
				{
					list.Add(new SysAuthorityTemplateEntity
					{
						Ignore = state,
						Id = x
					});
				});
				return this._dbSugar.Updateable(list).UpdateColumns((SysAuthorityTemplateEntity x) => new { x.Ignore }).ExecuteCommand();
			}
			case 2:
			{
				List<SysRoleAuthorityEntity> list2 = new List<SysRoleAuthorityEntity>();
				pkList.ForEach(delegate(int x)
				{
					list2.Add(new SysRoleAuthorityEntity
					{
						Ignore = state,
						Id = x
					});
				});
				return this._dbSugar.Updateable(list2).UpdateColumns((SysRoleAuthorityEntity x) => new { x.Ignore }).ExecuteCommand();
			}
			default:
			{
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(8, 1);
				defaultInterpolatedStringHandler.AppendLiteral("无效的flag=");
				defaultInterpolatedStringHandler.AppendFormatted(flag);
				throw new Exception(defaultInterpolatedStringHandler.ToStringAndClear());
			}
			}
		}

		public void Clear(List<string> assemblyBuff)
		{
			SqlSugarClientEx sugar = DbUtility.GetSugar(Catastrophe.Initialize.SystemIni.FileConfigIni.GetDbAppConfig, isAutoCloseCon: true);
			try
			{
				sugar.BeginTran();
				(from x in sugar.Deleteable<SysRoleAuthorityEntity>()
					where !SqlFunc.ContainsArray(assemblyBuff.ToArray(), x.AssemblyName)
					select x).ExecuteCommand();
				(from x in sugar.Deleteable<SysAuthorityTemplateEntity>()
					where !SqlFunc.ContainsArray(assemblyBuff.ToArray(), x.AssemblyName)
					select x).ExecuteCommand();
				sugar.CommitTran();
			}
			catch (Exception)
			{
				sugar.RollbackTran();
			}
		}
	}
}
